package com.coding365.consumer.util;


import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class TimeSchedule implements CommandLineRunner {

    private static AtomicInteger tick = new AtomicInteger(0);

    private static AtomicBoolean newSecond = new AtomicBoolean(true);

    //判断当前时间是否是新的一秒
    public static Boolean isCurrentNewSecond(){
        return newSecond.get();
    }

    public static int getTick() {
        newSecond.set(false);
        return tick.get();
    }

    @Override
    public void run(String... args) {
        //启动定时调度器,每秒中增加计数器
        ScheduledExecutorService service = Executors
                .newSingleThreadScheduledExecutor();
        service.scheduleWithFixedDelay(() ->{
            newSecond.set(true);
            tick.addAndGet(1);
        },1,1,TimeUnit.SECONDS);
    }
}
